package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"xialou_platform/app/errorx"
	"xialou_platform/services/address/model"
	"xialou_platform/services/address/rpc/internal/svc"
	"xialou_platform/services/address/rpc/pb"
)

type QueryCountysLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryCountysLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryCountysLogic {
	return &QueryCountysLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryCountysLogic) QueryCountys(in *pb.CodeReq) (*pb.ListResp, error) {
	// todo: add your logic here and delete this line
	res, err := l.svcCtx.CountyModel.FindListByCityCode(in.Code)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, errorx.NewMsgCodeError(errorx.NotFoundResourceCode, "区县不存在")
		}
		return nil, errorx.NewCodeReason(errorx.DBErrorCode, err.Error())
	}

	rspArr := make([]*pb.AddressResp, 0)
	for _, county := range res {
		rsp := pb.AddressResp{
			Id:        county.Id,
			Name:      county.Name,
			Code:      county.CountyId,
			SuperCode: county.CityId,
		}
		rspArr = append(rspArr, &rsp)
	}
	return &pb.ListResp{List: rspArr}, nil
}
